package com.lanvideo.service;

import com.lanvideo.dao.LearningRecordDao;
import com.lanvideo.entity.LearningRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 学习记录服务
 */
@Service
public class LearningRecordService {

    @Autowired
    private LearningRecordDao learningRecordDao;

    /**
     * 开始学习
     */
    public void startLearning(Integer userId, Integer videoId) {
        learningRecordDao.createLearningRecord(userId, videoId);
    }

    /**
     * 更新学习进度
     */
    public void updateLearningProgress(Integer userId, Integer videoId, Integer duration, 
                                     Integer lastPosition) {
        learningRecordDao.updateLearningProgress(userId, videoId, duration, lastPosition);
    }

    /**
     * 完成学习
     */
    public void completeLearning(Integer userId, Integer videoId) {
        learningRecordDao.completeLearning(userId, videoId);
    }

    /**
     * 获取用户的学习记录
     */
    public List<LearningRecord> getUserLearningRecords(Integer userId) {
        return learningRecordDao.getUserLearningRecords(userId);
    }

    /**
     * 获取视频的学习记录
     */
    public List<LearningRecord> getVideoLearningRecords(Integer videoId) {
        return learningRecordDao.getVideoLearningRecords(videoId);
    }

    /**
     * 获取用户对特定视频的学习记录
     */
    public LearningRecord getUserVideoLearningRecord(Integer userId, Integer videoId) {
        return learningRecordDao.getUserVideoLearningRecord(userId, videoId);
    }

    /**
     * 获取用户的学习统计
     */
    public LearningRecord getUserLearningStats(Integer userId) {
        return learningRecordDao.getUserLearningStats(userId);
    }

    /**
     * 删除学习记录
     */
    public boolean deleteLearningRecord(Integer id) {
        int result = learningRecordDao.deleteLearningRecord(id);
        return result > 0;
    }

    /**
     * 获取最近学习记录
     */
    public List<LearningRecord> getRecentLearningRecords(Integer userId, int limit) {
        return learningRecordDao.getRecentLearningRecords(userId, limit);
    }

    /**
     * 计算学习进度
     */
    public BigDecimal calculateProgress(Integer currentPosition, Integer totalDuration) {
        if (totalDuration == null || totalDuration <= 0) {
            return BigDecimal.ZERO;
        }
        if (currentPosition == null || currentPosition <= 0) {
            return BigDecimal.ZERO;
        }
        
        BigDecimal progress = new BigDecimal(currentPosition)
                .divide(new BigDecimal(totalDuration), 4, java.math.RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100));
        
        return progress.min(new BigDecimal(100));
    }
}
